<?php

namespace Admin\Models;

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\SoftDelete;
use Helpers\User;

class Base extends Model
{

    /**
     * 初始化软删除
     *
     * create by ck 20181121
     */
    public function initialize()
    {
        $this->useDynamicUpdate(true);
//        $this->keepSnapshots(false);
        if (property_exists($this, 'isDel')) {
            $this->addBehavior(new SoftDelete([
                'field' => 'isDel',
                'value' => 1,
            ]));
        }
    }

    /**
     * 获取保存错误原因
     *
     * @return string
     *
     * create by ck 20181121
     */
    public function getError()
    {
        $message = parent::getMessages()[0];
        return $message->getMessage();
    }

    /**
     * 根据id删除记录
     *
     * @param $idArr
     * @return bool
     *
     * create by ck 20180322
     */
    public static function deleteById($idArr)
    {
        if (!$idArr) {
            return false;
        }
        return self::find([
            'conditions' => "isDel = 0 AND id IN ({idArr:array})",
            'bind'       => ['idArr' => $idArr]
        ])->delete();
    }

    /**
     * 创建前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20181121
     */
    public function beforeCreate()
    {
        $userId  = User::getId();
        $time    = time();
        if (property_exists($this, 'isDel')) {
            $this->writeAttribute('isDel', 0);
        }
        if (property_exists($this, 'createAt')) {
            $this->writeAttribute('createAt', $time);
        }
        if (property_exists($this, 'createBy')) {
            $this->writeAttribute('createBy', $userId);
        }
        if (property_exists($this, 'updateAt')) {
            $this->writeAttribute('updateAt', date('Y-m-d H:i:s'));
        }
        if (property_exists($this, 'updateBy')) {
            $this->writeAttribute('updateBy', $userId);
        }
        return true;
    }

    /**
     * 更新前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20181121
     */
    public function beforeUpdate()
    {
        if (property_exists($this, 'updateAt')) {
            $this->writeAttribute('updateAt', date('Y-m-d H:i:s'));
        }
        if (property_exists($this, 'updateBy')) {
            $this->writeAttribute('updateBy', User::getId());
        }
        return true;
    }

    /**
     * 删除前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20181121
     */
    public function beforeDelete()
    {
        $this->beforeUpdate();
        return true;
    }
}
